package xyz.suancaiyu.eurekazuulclient.hystrix;


import org.springframework.cloud.netflix.zuul.filters.route.FallbackProvider;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.stereotype.Component;

import java.io.ByteArrayInputStream;
import java.io.InputStream;


/**
 *  在Zuul中使用熔断器.
 *
 *
 *
 *
 *             zuul:
 *               routes:
 *                 hiapi:
 *                   path: /hiapi/**
 *                   serviceId: hiapi-v1
 *                 ribbonapi:
 *                   path: /ribbonapi/**
 *                   serviceId: eureka-ribbon-client
 *                 feignapi:
 *                   path: /feignapi/**
 *                   serviceId: eureka-feign-client
 * getRoute()方法中,需要填写serviceId,或者"*"为所有路由服务都加熔断功能.
 *
 *
 */
@Component
public class MyFallbackProvider implements FallbackProvider {


    @Override
    public String getRoute() {
        // 所有的路由服务都加熔断功能: return "*";
        // 下面这个地方填写serviceId.
        return "eureka-client";
    }


    @Override
    public ClientHttpResponse fallbackResponse(String route, Throwable cause) {
        return new ClientHttpResponse() {
            @Override
            public HttpStatus getStatusCode() {
                return HttpStatus.OK;
            }

            @Override
            public int getRawStatusCode() {
                return 200;
            }

            @Override
            public String getStatusText() {
                return "OK";
            }

            @Override
            public void close() {
            }

            @Override
            public InputStream getBody() {
                return new ByteArrayInputStream("[eureka-zuul-client]oooops!error, i'm the fallback.".getBytes());
            }

            @Override
            public HttpHeaders getHeaders() {
                HttpHeaders headers = new HttpHeaders();
                headers.setContentType(MediaType.APPLICATION_JSON);
                return headers;
            }
        };
    }
}
